package bar;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.security.KeyStore;
import java.security.SecureRandom;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;


public class SocketTest {

	public static void main(String[] args) throws Exception {
	
		SSLSocketFactory sf = createSslFactory();
		Socket s = sf.createSocket();
		s.connect(new InetSocketAddress("127.0.0.1", 6811));
		
		s.getOutputStream().write("bleh".getBytes());
		s.getOutputStream().flush();
		System.out.println(s.getInputStream().read());
	}

	private static SSLSocketFactory createSslFactory(){
		try{
			String jksPath = "c:/jlee/tmp/jeopardytrust.jks";
			
			
			char[] keyPassword = "yes a secure password!".toCharArray();
			
			FileInputStream keyFile = new FileInputStream(jksPath); 
	
			KeyStore keyStore = KeyStore.getInstance("JKS");
			keyStore.load(keyFile, keyPassword);
			 
			KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
			keyManagerFactory.init(keyStore, keyPassword);
			 
			KeyManager keyManagers[] = keyManagerFactory.getKeyManagers();
			
			TrustManagerFactory tmf =TrustManagerFactory.getInstance("SunX509");
			tmf.init(keyStore);
			TrustManager tms[] = tmf.getTrustManagers();
			
			SSLContext sslContext = SSLContext.getInstance("SSLV3");
			//sslContext.init(keyManagers, null, new SecureRandom());
			sslContext.init(null, tms, new SecureRandom());
			SSLSocketFactory socketFactory = sslContext.getSocketFactory();
	
			keyFile.close();
			
			return socketFactory;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
}
